package com.guigu.service.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.entity.Users;
import com.guigu.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("自定义登录");
        //根据用户名查询
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq(Users.USERNAME, s);
        Users user = usersMapper.selectOne(wrapper);
        System.out.println(user);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在!!!");
        }
        //admins emp ROLE_salary   ROLE_update,ROLE_up
        List<GrantedAuthority> auths = AuthorityUtils
                .commaSeparatedStringToAuthorityList("ROLE_update,ROLE_up,ROLE_salary");
        String pwd = new BCryptPasswordEncoder().encode(user.getPassword());
        return new User(user.getUsername(),
                pwd,
                auths);
    }
}
